package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.CategoryService;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增分类
     *
     * @param category
     * @param httpSession
     * @return
     */
    @PostMapping
    public R add(@RequestBody Category category) {
        //category.setCreateTime(LocalDateTime.now());
        //category.setUpdateTime(LocalDateTime.now());
        //Employee loginEmployee = (Employee) httpSession.getAttribute("loginEmployee");
        //category.setCreateUser(loginEmployee.getId());
        //category.setUpdateUser(loginEmployee.getId());
        boolean result = categoryService.save(category);
        return result ? R.success("新增分类成功") : R.error("新增分类失败");
    }

    /**
     * 分页展示
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R getByPage(int page, int pageSize) {
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.orderByAsc(Category::getSort);
        IPage<Category> pageInfo = new Page<>(page, pageSize);
        categoryService.page(pageInfo, lqw);
        return R.success(pageInfo);
    }

    /**
     * 删除分类
     *
     * @param id
     * @return
     */
    @DeleteMapping
    public R deleteById(Long id) {
        R delete = categoryService.delete(id);
        return delete;
    }

    /**
     * 修改分类
     * @param category
     * @return
     */
    @PutMapping
    public R updateById(@RequestBody Category category) {
        boolean result = categoryService.updateById(category);
        return result ? R.success("修改分类成功") : R.error("修改失败");
    }

    @GetMapping("/list")
    public R getList(Category category){
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.eq(category.getType()!=null,Category::getType,category.getType());
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(lqw);
        return R.success(list);

    }

}
